package org.common.middlewave;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.common.utils.ApiResponse;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 全局的异常捕捉处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * @param ex
     * @return
     */

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ApiResponse> handleValidationExceptions(MethodArgumentNotValidException ex) {
        List<String> messages = ex.getBindingResult().getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.toList());
        String message = String.join(",", messages);
        return new ResponseEntity<>(new ApiResponse(HttpStatus.BAD_REQUEST.value(), message, new HashMap<String, String>()), HttpStatus.BAD_REQUEST);
    }

    // 处理其他异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiResponse> handleAllExceptions(Exception ex) {
        return new ResponseEntity<>(new ApiResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage(), new HashMap<String, String>()), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}